.equ CSR_MATP, 0xBC0

# NOTE : TO CHANGE USER PROGRAM'S REGISTERS
# JUST SAVE THE NEW VALUES INTO THE TRAPFRAME

.section trampsec
.globl trampoline
trampoline:
.align 4
.globl uservec
uservec:    
        # a0 <- *mscratch = TRAPFRAME
        # mscratch <- *a0
        csrrw a0, mscratch, a0
        sw ra, 0(a0)
        sw sp, 4(a0)
        sw gp, 8(a0)
        sw tp, 12(a0)
        sw t0, 16(a0)
        sw t1, 20(a0)
        sw t2, 24(a0)
        sw s0, 28(a0)
        sw s1, 32(a0)
        # sw a0, 36(a0)
        sw a1, 40(a0)
        sw a2, 44(a0)
        sw a3, 48(a0)
        sw a4, 52(a0)
        sw a5, 56(a0)
        sw a6, 60(a0)
        sw a7, 64(a0)
        sw s2, 68(a0)
        sw s3, 72(a0)
        sw s4, 76(a0)
        sw s5, 80(a0)
        sw s6, 84(a0)
        sw s7, 88(a0)
        sw s8, 92(a0)
        sw s9, 96(a0)
        sw s10, 100(a0)
        sw s11, 104(a0)
        sw t3, 108(a0)
        sw t4, 112(a0)
        sw t5, 116(a0)
        sw t6, 120(a0)
        # trapframe 124: kernel stack pointer
        # trapframe 128: usertrap entry
        # trapframe 132: kernel pagetable
        # trapframe 136: arg
        csrr t0, mscratch # t0 = a0
        sw t0, 36(a0)
        lw sp, 124(a0) # kernel stack pointer !!! IMPORTANT: ksp is always KSTACK(PID)
        lw t0, 132(a0) # kernel pagetable
        lw t1, 128(a0) # usertrap entry
        csrw CSR_MATP, t0 # switch to kernel pagetable
        # do not need fence.vma
        jr t1
        

.globl userret
userret:
        # userret(TRAPFRAME, pagetable)
        csrw CSR_MATP, a1 # switch to user pagetable
        # do not need fence.vma
        lw t0, 36(a0)
        csrw mscratch, t0 #put saved a0 into mscratch
        lw ra, 0(a0)
        lw sp, 4(a0)
        lw gp, 8(a0)
        lw tp, 12(a0)
        lw t0, 16(a0)
        lw t1, 20(a0)
        lw t2, 24(a0)
        lw s0, 28(a0)
        lw s1, 32(a0)
        # lw a0, 36(a0)
        lw a1, 40(a0)
        lw a2, 44(a0)
        lw a3, 48(a0)
        lw a4, 52(a0)
        lw a5, 56(a0)
        lw a6, 60(a0)
        lw a7, 64(a0)
        lw s2, 68(a0)
        lw s3, 72(a0)
        lw s4, 76(a0)
        lw s5, 80(a0)
        lw s6, 84(a0)
        lw s7, 88(a0)
        lw s8, 92(a0)
        lw s9, 96(a0)
        lw s10, 100(a0)
        lw s11, 104(a0)
        lw t3, 108(a0)
        lw t4, 112(a0)
        lw t5, 116(a0)
        lw t6, 120(a0)
        csrrw a0, mscratch, a0 # swap TRAMPFRAME and saved-a0
        mret